The problem can be found at the following link: Question Link
To solve the matchsticks game, I have used the following approach:
- It is observed that if the number
n
is a multiple of5
, then playerB
will win because playerA
will have to pick the last matchstick and playerB
will always have a winning move. - Otherwise, if
n
is not a multiple of5
, playerA
will choose a number equal ton%5
to ensure their victory. This way, playerA
can force playerB
into a losing position by making the remaining number a multiple of5
in the next turn.
- Time Complexity:
O(1)
because the calculations are performed in constant time. - Auxiliary Space Complexity:
O(1)
as we are not using any extra space that scales with the input.
class Solution {
public:
int matchGame(long long n) {
if(n % 5)
return n % 5;
return -1;
}
};
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.